#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

// 解析命令行参数
const args = process.argv.slice(2);
const options = {
  backend: args.includes('--backend') || args.includes('-b'),
  frontend: args.includes('--frontend') || args.includes('-f'),
  coverage: args.includes('--coverage') || args.includes('-c'),
  watch: args.includes('--watch') || args.includes('-w'),
  verbose: args.includes('--verbose') || args.includes('-v')
};

// 如果没有指定，默认运行所有测试
if (!options.backend && !options.frontend) {
  options.backend = true;
  options.frontend = true;
}

console.log('🧪 开始运行测试...\n');

async function runCommand(command, args, cwd, label) {
  return new Promise((resolve, reject) => {
    console.log(`\n🔄 ${label}...`);
    console.log(`执行: ${command} ${args.join(' ')}`);
    console.log(`目录: ${cwd}\n`);

    const child = spawn(command, args, {
      cwd,
      stdio: 'inherit',
      shell: true
    });

    child.on('close', (code) => {
      if (code === 0) {
        console.log(`\n✅ ${label} 完成`);
        resolve();
      } else {
        console.log(`\n❌ ${label} 失败 (退出码: ${code})`);
        reject(new Error(`${label} failed with code ${code}`));
      }
    });

    child.on('error', (error) => {
      console.error(`\n❌ ${label} 错误:`, error);
      reject(error);
    });
  });
}

async function runTests() {
  const results = {
    backend: null,
    frontend: null
  };

  try {
    // 运行后端测试
    if (options.backend) {
      const backendPath = path.join(__dirname, '../backend');
      const backendArgs = ['test'];
      
      if (options.coverage) {
        backendArgs.push('--coverage');
      }
      if (options.watch) {
        backendArgs.push('--watch');
      }
      if (options.verbose) {
        backendArgs.push('--verbose');
      }

      try {
        await runCommand('npm', backendArgs, backendPath, '后端测试');
        results.backend = 'success';
      } catch (error) {
        results.backend = 'failed';
        if (!options.frontend) {
          throw error;
        }
      }
    }

    // 运行前端测试
    if (options.frontend) {
      const frontendPath = path.join(__dirname, '../frontend');
      const frontendArgs = ['test'];
      
      if (options.coverage) {
        frontendArgs.push('--coverage');
      }
      if (options.watch) {
        frontendArgs.push('--watch');
      }
      if (options.verbose) {
        frontendArgs.push('--verbose');
      }

      try {
        await runCommand('npm', frontendArgs, frontendPath, '前端测试');
        results.frontend = 'success';
      } catch (error) {
        results.frontend = 'failed';
        if (!options.backend || results.backend === 'failed') {
          throw error;
        }
      }
    }

    // 生成测试报告
    if (options.coverage) {
      console.log('\n📊 生成测试报告...');
      
      const reportPath = path.join(__dirname, '../test-reports');
      if (!fs.existsSync(reportPath)) {
        fs.mkdirSync(reportPath, { recursive: true });
      }

      // 复制覆盖率报告
      const backendCoverage = path.join(__dirname, '../backend/coverage');
      const frontendCoverage = path.join(__dirname, '../frontend/coverage');
      
      if (fs.existsSync(backendCoverage)) {
        console.log('✅ 后端覆盖率报告: backend/coverage/lcov-report/index.html');
      }
      
      if (fs.existsSync(frontendCoverage)) {
        console.log('✅ 前端覆盖率报告: frontend/coverage/lcov-report/index.html');
      }
    }

    // 输出结果摘要
    console.log('\n📋 测试结果摘要:');
    if (options.backend) {
      console.log(`  后端测试: ${results.backend === 'success' ? '✅ 通过' : '❌ 失败'}`);
    }
    if (options.frontend) {
      console.log(`  前端测试: ${results.frontend === 'success' ? '✅ 通过' : '❌ 失败'}`);
    }

    const allPassed = (!options.backend || results.backend === 'success') && 
                     (!options.frontend || results.frontend === 'success');

    if (allPassed) {
      console.log('\n🎉 所有测试通过！');
      process.exit(0);
    } else {
      console.log('\n💥 部分测试失败');
      process.exit(1);
    }

  } catch (error) {
    console.error('\n💥 测试运行失败:', error.message);
    process.exit(1);
  }
}

// 显示帮助信息
if (args.includes('--help') || args.includes('-h')) {
  console.log(`
测试运行器使用说明:

用法: node scripts/run-tests.js [选项]

选项:
  -b, --backend     只运行后端测试
  -f, --frontend    只运行前端测试
  -c, --coverage    生成测试覆盖率报告
  -w, --watch       监听模式（文件变化时自动重新运行）
  -v, --verbose     详细输出
  -h, --help        显示帮助信息

示例:
  node scripts/run-tests.js                    # 运行所有测试
  node scripts/run-tests.js --backend          # 只运行后端测试
  node scripts/run-tests.js --coverage         # 运行测试并生成覆盖率报告
  node scripts/run-tests.js --watch --frontend # 监听模式运行前端测试
`);
  process.exit(0);
}

// 运行测试
runTests();